package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author LQQ
 * @Date 2020/3/10 14:37
 * @Version 1.0
 */

@Controller
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private AuthService authService;
    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;


    /**
     * 跳转到登入页面
     * @return
     */
    @RequestMapping("/toLogin")
    //@RequestParam声明这个参数不是必须传递的
    public String toLogin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model){

        model.addAttribute("from",from);

        return "login";
    }


    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) {
        //1. 校验参数
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }

        //2. 申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //3. 将jti的值存入cookie中
        this.saveJtiToCookie(authToken.getJti(), response);

        //4. 返回结果
        return new Result(true, StatusCode.OK, "登入成功",authToken.getJti());
    }


    // 将令牌的短标识jti存入到cookie中
    private void saveJtiToCookie(String jti, HttpServletResponse response) {
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);

    }

}
